<template>
	<view class="link-page">
		<view class="app-title ac">
			<view class="fl" @click="back">
				<image class="back" src="/static/img/back.png"></image>
			</view>{{ pageTitle }}
		</view>
		<web-view v-if="wvSrc" ref="webView" class="webViewClass" :src="wvSrc" :webview-styles="webviewStyles"
			@message="getMessage"></web-view>
	</view>
</template>

<script>
	var wv; // 计划创建的webview
	var currentWebview;
	import {
		WORK_CONTROLLER
	} from "../../api/pms";

	import NFC from "../../utils/nfc.js";

	function getExtraParam(options, url) {
		let query = "";
		if (url.indexOf("?") == -1) {
			query = "?";
		} else {
			if (url.endsWith("?")) {
				query = "";
			} else {
				query = "&";
			}
		}
		if (options.title == "相关标准化资料") {
			return `${url}${query}equId=${options.equId}&station=${options.station}`;
		}
		return url;
	}

	export default {
		data() {
			return {
				curWebview: null,
				pageTitle: "",
				wvSrc: "",
				webviewStyles: {
					top: "66px",
				},
			};
		},
		onLoad(options) {
			this.pageTitle = options.title || "链接";
			this.wvSrc = "";
			if (options.url) {
				let query = "";

				if (options.openType == 6) {
					query = "&";
					let info = this.$store.state.userInfo;
					let token = this.$store.state.token;
					if (options.url.indexOf("?") == -1) {
						query = "?";
					} else {
						if (options.url.endsWith("?")) {
							query = "";
						} else {
							query = "&";
						}
					}
					let roleCode = (info.roles && info.roles[0] && info.roles[0]) || {};
					let orgInfo = info.org || {};
					console.log(info, "info");
					console.log(token, "token");
					query +=
						`user_id=${info.id}&user_name=${info.account}&role_name=${roleCode.name}&org_id=${orgInfo.idK}&org_num=${orgInfo.num}&org_type_code=${orgInfo.orgtypeCode}&major=${roleCode.major}&role_code=${roleCode.code}&labelcode=${options.equCode}&token=${token}`;
				}
				this.wvSrc = getExtraParam(options, `${options.url}${query}`);
				setTimeout(() => {
					// 获取当前页面的webview对象
					this.getWebView(); // 如果是页面初始化调用时，需要延时一下
				}, 1000);
				console.log(query);
				console.log("wvSrc:", this.wvSrc);
			} else {
				console.error("缺少url");
			}
		},
		mounted() {
			// #ifdef H5
			window.addEventListener("message", async (e) => {
				console.log("父组件收到数据了", e.data);
				//	this.passChangeNode(e.data)
				let param = e.data;
				if (e.data.inputType == "ScanningCode") {
					let result = await this.scanCode();
					this.passMessage({
						inputType: e.data.inputType,
						resultType: e.data.resultType,
						data: result,
						userName: this.$store.state.userInfo.name,
						userId: this.$store.state.userInfo.id,
					});
				}
				if (e.data.inputType == "NFCIdentify") {
					let result = await this.testNFC();
					this.passMessage({
						inputType: e.data.inputType,
						resultType: e.data.resultType,
						data: result,
						userName: this.$store.state.userInfo.name,
						userId: this.$store.state.userInfo.id,
					});
				}
				if (e.data.inputType == "location") {
					let res = await this.getPosition();
					this.passMessage({
						inputType: e.data.inputType,
						resultType: e.data.resultType,
						data: res,
						userName: this.$store.state.userInfo.name,
						userId: this.$store.state.userInfo.id,
					});
				}
			});
			// #endif
			// #ifdef APP-PLUS
			let _this = this;
			uni.getSystemInfo({
				success(res) {
					console.log(res); //手机牌子
					console.log(res.model); //手机型号
					console.log(res.screenWidth); //屏幕宽度
					console.log(res.screenHeight); //屏幕高度
					let height = res.screenHeight;
					let windownHeight = res.windowHeight;
					let childHeight = windownHeight - 66;
					setTimeout(() => {
						_this.curWebview = _this.$scope.$getAppWebview().children()[0];
						_this.curWebview.setStyle({
							height: childHeight + "px",
							// height: "200px"
						});
						console.log(
							"页面高度",
							childHeight + "px",
							_this.curWebview.setStyle
						);
					}, 1000);
				},
			});
			// #endif
		},
		methods: {
			getLocationUtil() {
				return new Promise((resolve, reject) => {
					uni.showToast({
						title: "获取位置信息中...",
						icon: "none",
					});
					// #ifdef APP-PLUS
					uni.getLocation({
						type: "gcj02",
						geocode: "true",
						success: function(res) {
							resolve({
								longitude: res.longitude,
								latitude: res.latitude,
							});
						},
						// 定位失败
						fail: function(error) {
							console.log(error);
							uni.showModal({
								title: "提示",
								content: error.errMsg,
							});
							reject(error);
						},
					});
					// #endif
				});
			},
			async getReturnLocation(param, param1) {
				console.log("param--param", param, param1);
				await this.fetch(
						"Get",
						this.$store.state.baseUrl + WORK_CONTROLLER.Get_zc_JudgeInRaw,
						param
					)
					.then(async (res) => {
						console.log(res);
						if (
							res.success &&
							res.data.inRawLocation != "NO" &&
							res.data.have == "YES"
						) {
							this.passMessage(param1);
						} else if (
							res.success &&
							res.data.inRawLocation == "NO" &&
							res.data.have == "YES"
						) {
							uni.showToast({
								title: "该标签所在地点不对",
								icon: "none",
							});
						} else if (res.success && res.data.have == "NO") {
							// uni.showToast({
							// 	title: '该标签不存在',
							// 	icon: 'none'
							// })
						} else {
							uni.showToast({
								title: res.message,
								icon: "none",
							});
						}
					})
					.catch((error) => {
						console.log(error);
					});
			},
			async handleScan(node) {
				if (node.inputType == "ScanningCode") {
					let result = await this.scanCode();
					console.log(result);
					this.passMessage({
						inputType: node.inputType,
						resultType: node.resultType,
						data: result,
						userName: this.$store.state.userInfo.name,
						userId: this.$store.state.userInfo.id,
					});
					// let loPram = await this.getLocationUtil().then(resLocal => {
					// 	let params = {
					// 		longitude: resLocal.longitude,
					// 		latitude: resLocal.latitude,
					// 		zcCode: result
					// 	}
					// 	return params
					// })
					// await this.getReturnLocation(loPram, {
					// 	inputType: node.inputType,
					// 	resultType: node.resultType,
					// 	data: result,
					// 	userName: this.$store.state.userInfo.name,
					// 	userId: this.$store.state.userInfo.id
					// })
				}
			},
			async handleNfc(node) {
				if (node.inputType == "NFCIdentify") {
					let result = await this.testNFC();
					console.log(result);
					this.passMessage({
						inputType: node.inputType,
						resultType: node.resultType,
						data: result,
						userName: this.$store.state.userInfo.name,
						userId: this.$store.state.userInfo.id,
					});
					// if (!result) return
					// let loPram = await this.getLocationUtil().then(resLocal => {
					// 	let params = {
					// 		longitude: resLocal.longitude,
					// 		latitude: resLocal.latitude,
					// 		zcCode: result
					// 	}
					// 	return params
					// })
					// await this.getReturnLocation(loPram, {
					// 	inputType: node.inputType,
					// 	resultType: node.resultType,
					// 	data: result,
					// 	userName: this.$store.state.userInfo.name,
					// 	userId: this.$store.state.userInfo.id
					// })
				}
			},
			async handleLocation(node) {
				if (node.inputType == "location") {
					let res = await this.getPosition();
					console.log(res);
					this.passMessage({
						inputType: node.inputType,
						resultType: node.resultType,
						data: res,
						userName: this.$store.state.userInfo.name,
						userId: this.$store.state.userInfo.id,
					});
				}
			},
			handlePreview(node) {
				console.log(node)
				if (node.inputType == 'video') {
					uni.navigateTo({
						url: "/pages/previewVideo/previewVideo?url=" + node.url,
					});
				} else if (node.inputType == "file") {
					uni.downloadFile({
						url: node.url,
						success: function(res) {
							console.log(res)
							var filePath = res.tempFilePath;
							uni.openDocument({
								filePath: filePath,
								showMenu: false,
								success: function(res) {
									console.log('打开文档成功');
								},
								fail: function(err) {
									console.log(err)
								}
							});
							console.log(filePath)

						},
						fail: function(err) {
							console.log(err, 3)

						}
					});
				}
			},
			handSure(node) {
				if (node === "Queren") {
					this.back()
				}
			},
			//报表给app传参数的真正作用函数，与上述mounted无关，重要！！！
			getMessage(e) {
				console.log(e)
				console.log("接收到消息了---1111--", JSON.stringify(e.detail.data[0]));
				let passValue = e.detail.data[0].message;
				let node = passValue;
				this.handleScan(node);
				this.handleNfc(node);
				this.handleLocation(node);
				this.handlePreview(node);
				this.handSure(node);
			},
			passMessage(param) {
				// #ifdef APP-PLUS
				setTimeout(() => {
					this.curWebview = this.$scope.$getAppWebview().children()[0];
					this.curWebview.evalJS(`uniToFanRuanEvent(${JSON.stringify(param)})`);
				}, 500);
				// #endif
			},
			async testNFC() {
				//这里用异步获取读取到的NFC数据
				const nfcId = await NFC.listenNFCStatus();
				// uni.showToast({
				// 	icon: "none",
				// 	title: nfcId,
				// })
				console.log(nfcId);
				if (!nfcId) {
					return "";
				} else {
					return nfcId;
				}
			},
			scanCode() {
				let _this = this;
				let code;
				return new Promise((resolve, reject) => {
					uni.scanCode({
						success: function(res) {
							console.log("设备扫码---", res);
							code = res.result;
							resolve(res.result);
						},
					});
				});
			},
			getPosition() {
				let code;
				return new Promise((resolve, reject) => {
					uni.getLocation({
						type: "gcj02",
						geocode: true, //获取城市具体地址
						success: (res) => {
							console.log("当前位置的经度：" + res.longitude);
							console.log("当前位置的纬度：" + res.latitude);
							code = "(" + res.longitude + "," + res.latitude + ")";
							resolve(code);
						},
						fail: function(res) {
							console.error(res);
							reject(res);
						},
					});
				});
			},
			getWebView() {
				// #ifdef APP-PLUS
				currentWebview = this.$scope.$getAppWebview();
				setTimeout(function() {
					wv = currentWebview.children()[0];
					wv &&
						wv.setStyle({
							scalable: true,
						});
				}, 500);
				// #endif
			},

			back() {
				if (this.pageTitle == "相关标准化资料") {
					uni.navigateBack();
				} else {
					uni.redirectTo({
						url: "/pages/index/index",
					});
				}
			},
		},
	};
</script>

<style lang="less" scoped>
	.webViewClass {
		height: calc(100vh - 66px);
		width: 100vw;
		top: 66px !important;
		padding-bottom: var(--window-bottom);
	}
</style>
<style>
	* {
		/* 取消点击背景色显示蓝色 */
		-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
	}
</style>